import { _decorator, Component, Node, AudioClip, Label, input, Input, EventKeyboard, AudioSource, KeyCode, instantiate, JsonAsset, Prefab, find } from 'cc';
const { ccclass, property } = _decorator;
import { Utils } from './Utils';
import { Monster } from './Monster';
import { Player } from './Player';
import { Boss } from './Boss';
import { Transition } from './Transition';
import { Blueprint } from './Blueprint';

/*
lp-intro-over Intro.ts
lp-color-data ColorBoard.ts
lp-weapon Intro.ts Game.ts
lp-backpack Backpack.ts
lp-equipment-bp-box EquipmentBpBox.ts
*/

@ccclass('GameManager')
export class GameManager extends Component {
    @property({type: Node})
    playerNode: Node = null!

    @property({type: Node})
    bossNode: Node = null!

    @property({type: Node})
    blueprintNode: Node = null!

    @property({type: Node})
    joystickNode: Node = null!

    @property({type: Node})
    attackButtonNode: Node = null!

    @property({type: Node})
    paintButtonNode: Node = null!

    @property({type: Node})
    enterButtonNode: Node = null!

    @property({type: Node})
    colorBaordScrollViewNode: Node = null!

    @property({type: Node})
    ToolBoxScrollViewNode: Node = null!

    @property({type: Node})
    backpackBoardNode: Node = null!

    @property({type: Node})
    aiResultBoardNode: Node = null!

    @property({type: Prefab})
    monsterPrefab: Prefab = null!

    @property({type: JsonAsset})
    equipmentJsonAsset: JsonAsset = null!

    @property({type: JsonAsset})
    monsterJsonAsset: JsonAsset = null!

    @property({type: AudioClip})
    clickAudio: AudioClip = null!

    utils: Utils = null!
    audioSource: AudioSource = null!

    isGamePaused: boolean = false
    isFightingBoss: boolean = false
    equipmentJsonData: object = null!
    monsterJsonData: object = null!

    start() {
        this.initComponents()
        this.initJsonData()
        this.checkIsBossDefeated()
    }

    /** 
     * @zh
     * 检查是否已经击败了Boss。
    */
    checkIsBossDefeated() {
        if (localStorage.getItem('lp-win')) {
            find('Canvas/Boss Door').active = false
            find('Canvas/Intro Label').active = true
            let playerNum = parseInt(localStorage.getItem('lp-win'))
            this.utils.showText(find('Canvas/Intro Label').getComponent(Label), `第${playerNum}位勇士，感谢你拯救了我们的世界!\n\n希望你开心快乐每一天~(●'◡'●)`)
        }
        else {
            this.showWelcomSign()
            this.spawnMonstersRandomly()
        }
    }

    /** 
     * @zh
     * 如果是新的勇士，显示欢迎信息。
    */
    showWelcomSign() {
        if (localStorage.getItem('lp-player-num')) {
            let playerNum = parseInt(localStorage.getItem('lp-player-num')) + 1
            this.utils.showFlashMessage(`欢迎第${playerNum}位勇士!`, 2)
        }
    }

    /** 
     * @zh
     * 初始化组件。
    */
    initComponents() {
        this.utils = this.node.getComponent(Utils)
        this.audioSource = this.getComponent(AudioSource)

        // 测试用
        // input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
    }

    /** 
     * @zh
     * 按键执行技能（测试用）。
    */
    onKeyDown(event:EventKeyboard) {
        switch(event.keyCode) {
            case KeyCode.KEY_A:
                // this.utils.showFlashMessage(`魔法光束!!!`, 2)
                find('Canvas/Player').getComponent(Player).showLightBeamAttack()
                break;
            case KeyCode.KEY_S:
                // this.utils.showFlashMessage(`火球术!!!`, 2)
                find('Canvas/Player').getComponent(Player).showFireballAttack()
                break
            case KeyCode.KEY_D:
                // this.utils.showFlashMessage(`闪电暴击!!!`, 2)
                find('Canvas/Player').getComponent(Player).showLightningAttack()
                break
            case KeyCode.KEY_F:
                // this.utils.showFlashMessage(`垃圾回收!!!`, 2)
                find('Canvas/Player').getComponent(Player).showTrashBinAttack()
                break
        }
    }

    /** 
     * @zh
     * 初始化Json数据变量。
    */
    initJsonData() {
        this.equipmentJsonData = this.equipmentJsonAsset.json
        this.monsterJsonData = this.monsterJsonAsset.json
    }

    /** 
     * @zh
     * 随机生成怪物。
    */
    spawnMonstersRandomly() {
        let callback = () => {
            // 主角处于死亡状态时不产生新的怪物
            // 在打Boss但Boss还没生气的时候不产生新的怪物
            if (this.playerNode.getComponent(Player).isDead || this.isFightingBoss && !this.bossNode.getComponent(Boss).isAngry) {
                return
            }

            let monster = instantiate(this.monsterPrefab)
            let randomIndex = Math.floor(Math.random() * Object.keys(this.monsterJsonData).length)
            let monsterInfo = this.monsterJsonData[`monster${randomIndex}`]
            monster.getComponent(Monster).setMonsterInfo(monsterInfo)
            this.node.addChild(monster)
        }

        // 立即生成一个怪物
        callback()

        // 使用计时器不断生成怪物
        this.schedule(()=>{
            let spawnTime = Math.random() * 8 + 5
            this.scheduleOnce(()=>{callback()}, spawnTime)
        }, 8)  // 时间可以考虑动态调整
    }

    /** 
     * @zh
     * 点击了绘制按钮。
    */
    onPaintButtonClicked() {
        this.audioSource.playOneShot(this.clickAudio)

        // 如果AI正在鉴定，则直接返回
        if (this.blueprintNode.getComponent(Blueprint).isAIChecking) {
            this.utils.showFlashMessage('AI正在鉴定中...', 1)
            return
        }
        
        // 显示或隐藏相关节点
        if (this.colorBaordScrollViewNode.active) {
            this.isGamePaused = false
            this.blueprintNode.parent.active = false
            this.colorBaordScrollViewNode.active = false
            this.ToolBoxScrollViewNode.active = false
            this.joystickNode.active = true
            this.attackButtonNode.active = true
        }
        else {
            this.isGamePaused = true // 游戏暂停
            this.blueprintNode.parent.active = true
            this.colorBaordScrollViewNode.active = true
            this.ToolBoxScrollViewNode.active = true
            this.joystickNode.active = false
            this.attackButtonNode.active = false
            this.backpackBoardNode.active = false
        }
    }

    /** 
     * @zh
     * 点击了背包按钮。
    */
    onBackpackButtonClicked() {
        this.audioSource.playOneShot(this.clickAudio)

        // 如果AI正在鉴定，则直接返回
        if (this.blueprintNode.getComponent(Blueprint).isAIChecking) {
            this.utils.showFlashMessage('AI正在鉴定中...', 1)
            return
        }

        // 显示或隐藏相关节点
        if (this.backpackBoardNode.active) {
            this.isGamePaused = false
            this.joystickNode.active = true
            this.attackButtonNode.active = true
            this.backpackBoardNode.active = false
            this.blueprintNode.parent.active = false
            this.colorBaordScrollViewNode.active = false
            this.ToolBoxScrollViewNode.active = false
        }
        else {
            this.isGamePaused = true
            this.joystickNode.active = false
            this.attackButtonNode.active = false
            this.backpackBoardNode.active = true
            this.blueprintNode.parent.active = false
            this.colorBaordScrollViewNode.active = false
            this.ToolBoxScrollViewNode.active = false
        }        
    }

    /** 
     * @zh
     * 玩家靠近门时，屏幕中间会显示按钮，玩家点击该按钮时执行的逻辑。
    */
    onEnterButtonClicked() {
        find('Canvas').getComponent(AudioSource).playOneShot(this.clickAudio)
        if (!localStorage.getItem('lp-intro-over')) {
            // 玩家可能想要在引导阶段就直接进门挑战Boss，此时需要提示
            // GameManger组件此时还未启用，所以用下其他组件的Utils
            find('Canvas/Player').getComponent(Player).utils.showFlashMessage('引导未结束')     
            return
        }

        // 嘎在门口的话不能进门
        if (this.playerNode.getComponent(Player).isDead) {
            return
        }

        // 打Boss
        if (!this.isFightingBoss) {
            this.playerNode.active = false
            find('Canvas/UI').active = false
            this.enterButtonNode.setPosition(100000, 100000, 0)
            this.node.getComponent(Transition).showTransition('warning', ()=>{
                this.isFightingBoss = true
                this.bossNode.active = true
                this.playerNode.active = true
                find('Canvas/UI').active = true
                this.enterButtonNode.setPosition(0, 0, 0)
                find('Canvas/UI/Boss ProgressBar').active = true
                this.enterButtonNode.children[0].getComponent(Label).string = '撤退!!!'
            })
        }

        // 从Boss房间退出
        else {
            this.playerNode.active = false
            find('Canvas/UI').active = false
            this.enterButtonNode.setPosition(100000, 100000, 0)
            this.node.getComponent(Transition).showTransition('exit', ()=>{
                this.isFightingBoss = false
                this.bossNode.active = false
                this.playerNode.active = true
                find('Canvas/UI').active = true
                this.enterButtonNode.setPosition(0, 0, 0)
                find('Canvas/UI/Boss ProgressBar').active = false
                this.enterButtonNode.children[0].getComponent(Label).string = '挑战大魔王'
            })
        }
        
        // 小怪、制作图、颜料全部消失，不然就带到了门的另一边，不合理
        for (let i=0; i<this.node.children.length; i++) {
            let item = this.node.children[i]
            if (item.name == 'monster' || item.name.indexOf('pixelItem') >-1 || item.name.indexOf('equipment-') > -1) {
                item.destroy()
            }
        }
    }

    update(deltaTime: number) {
        // 相关节点置顶
        if (this.blueprintNode.parent.active) {
            this.blueprintNode.parent.setSiblingIndex(5000)
            this.colorBaordScrollViewNode.setSiblingIndex(5000)
            this.ToolBoxScrollViewNode.setSiblingIndex(5000)
        }

        if (this.backpackBoardNode.active) {
            this.backpackBoardNode.setSiblingIndex(5000)
        }

        if (this.aiResultBoardNode.active) {
            this.aiResultBoardNode.setSiblingIndex(5000)
        }

        find("Canvas/Flash Board").setSiblingIndex(6000)
    }
}


